//
//  KABExhDetailVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/14.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABExhDetailVC.h"
#import "KABExhibitionTCell.h"
#import "KABExhBuyVC.h"
#import "KABExhSureOrderVC.h"
#import "KABExhDetBuyTCell.h"
#import "KABCosDetComHeaderHFView.h"
#import "KABExhDetDesTCell.h"
#import "KABExhDetGuestTCell.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "KSPhotoBrowser.h"

@interface KABExhDetailVC ()<UITableViewDelegate, UITableViewDataSource, KABExhDetBuyTCellDelegate, kABExhDetGuestTCellDelegate, KABExhibitionTCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

static NSString *const kReuseCellId = @"KABExhibitionTCell";
static NSString *const kBuyCellId = @"KABExhDetBuyTCell";
static NSString *const kDetDesCellId = @"KABExhDetDesTCell";
static NSString *const kGuestCellId = @"KABExhDetGuestTCell";
static NSString *const kDetComHeaderViewId = @"KABCosDetComHeaderHFView";

@implementation KABExhDetailVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = self.exhItem.name;
    
    if (self.presentingViewController) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBarBtnTapped:)];
    }
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //
    //    self.tableView.contentInset = UIEdgeInsetsMake(-64 * 2.0, 0, 49.0, 0);
    //    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 49.0, 0);
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    UINib *buyCellNib = [UINib nibWithNibName:kBuyCellId bundle:nil];
    [self.tableView registerNib:buyCellNib forCellReuseIdentifier:kBuyCellId];
    UINib *desCellNib = [UINib nibWithNibName:kDetDesCellId bundle:nil];
    [self.tableView registerNib:desCellNib forCellReuseIdentifier:kDetDesCellId];
    UINib *gusetCellNib = [UINib nibWithNibName:kGuestCellId bundle:nil];
    [self.tableView registerNib:gusetCellNib forCellReuseIdentifier:kGuestCellId];
    UINib *comHNib = [UINib nibWithNibName:kDetComHeaderViewId bundle:nil];
    [self.tableView registerNib:comHNib forHeaderFooterViewReuseIdentifier:kDetComHeaderViewId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 225.0;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 48.0;
    //    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
    //    self.tableView.estimatedSectionFooterHeight = 108.0;
    
//    self.tableView.tableHeaderView = self.headerBgView;
//    self.tableView.tableFooterView = self.footerBgView;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self requestExhibitionDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.exhItem.special_guest_list.count + 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABExhibitionTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        [cell configViewWithExhDetail:self.exhItem];
        cell.delegate = self;
        return cell;
    } else if (indexPath.section == 1) {
        KABExhDetBuyTCell *cell = [tableView dequeueReusableCellWithIdentifier:kBuyCellId forIndexPath:indexPath];
        [cell configViewWithExhListItem:self.exhItem];
        cell.delegate = self;
        return cell;
    } else if (indexPath.section == 2) {
        KABExhDetDesTCell *cell = [tableView dequeueReusableCellWithIdentifier:kDetDesCellId forIndexPath:indexPath];
        [cell configViewWithExhListItem:self.exhItem];
        return cell;
    }
    
    KABExhDetGuestTCell *cell = [tableView dequeueReusableCellWithIdentifier:kGuestCellId forIndexPath:indexPath];
    [cell configViewWithExhDetGuestItem:self.exhItem.special_guest_list[indexPath.section - 3]];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3) {
        KABCosDetComHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kDetComHeaderViewId];
        view.titleLabel.text = (section == 2) ? @"漫展详情" : @"漫展嘉宾";
        return view;
    }
    return nil;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
//    return view;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3) {
        return 50.0;
    }
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - KABExhibitionTCellDelegate
- (void)kABExhibitionTCell:(KABExhibitionTCell *)cell imgViewTapped:(UIImageView *)imgView {
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                    imageUrl:[NSURL URLWithString:self.exhItem.cover_image_url]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleScale;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

#pragma mark - KABCosDetailTCellDelegate
- (void)kABExhDetGuestTCell:(KABExhDetGuestTCell *)cell imgViewDownload:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath) {
        [self.tableView reloadData];
    }
}
- (void)kABExhDetGuestTCell:(KABExhDetGuestTCell *)cell imgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    KABExhDetGuestItem *item = self.exhItem.special_guest_list[indexPath.section - 3];;
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                    imageUrl:[NSURL URLWithString:item.image_url]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleScale;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

#pragma mark - KABExhDetBuyTCellDelegate
- (void)kABExhDetBuyTCell:(KABExhDetBuyTCell *)cell followBtnTapped:(UIButton *)btn {
    self.exhItem.is_collected = !self.exhItem.is_collected;
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
    [self requestFollowWithExhId:self.exhItem.exhibition_id isFollow:self.exhItem.is_collected];
}

- (void)kABExhDetBuyTCell:(KABExhDetBuyTCell *)cell buyBtnTapped:(UIButton *)btn {
    if (!self.exhItem.is_buyable) {
        return;
    }
    
    KABExhBuyVC *vc = [[KABExhBuyVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.exhItem = self.exhItem;
    vc.completeBlock = ^(){
        KABExhSureOrderVC *vc = [[KABExhSureOrderVC alloc] init];
        vc.exhItem = self.exhItem;
        [self showViewController:vc sender:nil];
    };
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - event response
- (void)editBarBtnTapped:(UIBarButtonItem *)item {
}

- (void)closeBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    self.navigationItem.title = self.exhItem.name;
    [self.tableView reloadData];
}

#pragma mark - network request
- (void)requestExhibitionDetail {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    NSInteger exhId = self.exhItem ? self.exhItem.exhibition_id : self.exhibition_id;
    [pars setObject:@(exhId) forKey:@"exhibition_id"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiExhibition] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求展会详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.exhItem = [KABExhListItem yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            self.exhItem.number = 1;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求展会详情失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestFollowWithExhId:(NSInteger)exhId isFollow:(BOOL)isFollow {
    // 关注必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"exhibition_id" : @(exhId),
                           @"is_collected" : isFollow ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiExhibitionCollect] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求关注返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            self.exhItem.is_collected = !isFollow;
            [self refreshWholeView];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求关注失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

@end
